package com.bing.my.controller;


import com.bing.common.config.Result;
import com.bing.my.entity.User;
import com.bing.my.service.UserService;
import com.bing.utils.JwtUtil;
import com.bing.utils.UtilConstants;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author bing
 * @since 2021-09-30
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;

    /**
    * 登录
    * @author Bing
    * @date 2021/10/03 12:44
     * @param user
    * @return com.bing.common.config.Result<?>
    */
    @PostMapping("/login")
    public Result<?> login(@Validated @RequestBody User user) {
        return userService.selectOne(user);
    }
    /**
    * 登录验证token
    * @author Bing
    * @date 2021/10/03 12:44
     * @param token
    * @return com.bing.common.config.Result<?>
    */
    @GetMapping("/info")
    public Result<?> info(@RequestParam("token") String token){
        // 验证token有效
        Claims claims = JwtUtil.parseJWT(UtilConstants.JWT_JWT_SEC, token);
        return userService.checkToken(claims);
    }
    @PostMapping("/logout")
    @RequiresAuthentication //必须登录后才能请求
    public Result<?> logout(@RequestHeader("X-Token") String token){
        return userService.logout(token);
    }

    /**
     * 增加用户接口
     *
     * @param user
     * @return
     */
    @PostMapping
    @RequiresRoles("admin") // 角色必须为admin
    public Result<?> insert(@RequestBody User user) {
        return userService.insert(user);
    }

    /**
     * 删除用户接口
     *
     * @param id
     * @return com.bing.common.config.Result<?>
     * @author Bing
     * @date 2021/09/30 16:50
     */
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        return userService.deleteById(id);
    }

    /**
     * 修改用户信息接口
     *
     * @param user
     * @return com.bing.common.config.Result<?>
     * @author Bing
     * @date 2021/09/30 16:50
     */
    @PutMapping
    public Result<?> update(@RequestBody User user) {
        return userService.update(user);
    }

    @RequestMapping(path = "/401")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<?> unauthorized() {
        return Result.error(500,"非法请求");
    }
}

